package Controller;


import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DAO.DAOFactory;
import DAO.HolidayDAO;
import Model.*;


/**
 * Servlet implementation class HolidayDetail
 */
@WebServlet("/HolidayDetail")
public class HolidayDetail extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Date Date = null;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HolidayDetail() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Authenticate(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Authenticate(request,response);
	}
	
	protected void Authenticate (HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		//Authenticate before starting process
		if ( LoginAdmin.CheckObject(request, response) ) {
			doProcess(request,response);
		} else {	//Otherwise Authentication Object not found
			response.sendRedirect(LoginAdmin.LOGIN_CONTROL);
		}
	}
	
	public void doProcess(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		LoginAdmin.CheckObject(request, response);
		String editHolidayId = request.getParameter("EditHolidayId");
		String isSubmit = request.getParameter("IsSubmit");
		String lastHolidayDate=request.getParameter("HolidayDate");
		Date parsedLastHolidayDate = null;
		String lastHolidayName = request.getParameter("HolidayName");
		String HolidayNameErrorMsg = "";
		String HolidayDateErrorMsg = "";
		boolean validatePass = false;
		//Edits should be submitted to Edits
		String actionTargetTail = "";
		String pageTitle = "";
		if (editHolidayId == null) {	//If this is "Add"
			pageTitle = "Add new Holiday";
		} else {					//Otherwise this is "Edit", add tail
			actionTargetTail = "?EditHolidayId="+editHolidayId;
			pageTitle = "Editting Holiday: "+editHolidayId;
		}
		
		//Functions for First Load
		if (isSubmit == null)			//If this is first load
		{
			validatePass = false;
			if (editHolidayId == null)	//If this is "Add Holiday"
			{
				lastHolidayName = "";	//Last Values are empty strings
				lastHolidayDate = "";
			}
			else						//Otherwise this is "Edit Holiday"
			{
				HolidayDAO holidayDAO = //get DAO
						DAOFactory.getInstance().getHolidayDAO();
				HolidayBean holiday = new HolidayBean();
				int holidayInt = Integer.parseInt(editHolidayId);
				try{
					holiday = holidayDAO.findByHolidayID(holidayInt);
				} catch (Exception e) {
					e.printStackTrace();
				}
				lastHolidayName = holiday.getHoliday_name();
				lastHolidayDate = holiday.getHoliday_date().toString();
			}
		}
		
		//Functions for Submission
		else	//Otherwise this is submission
		{		//Start Validation
			validatePass = true;
			lastHolidayDate = lastHolidayDate.trim();
			if (lastHolidayName.length() == 0)
			{ 
				HolidayNameErrorMsg = "Please enter a holiday name.";
				validatePass = false;
			}
			if(lastHolidayDate.length() == 0) {
				HolidayDateErrorMsg="Please enter a date. ";
				validatePass = false;
			} else {								//Parse Text Box into Date object
				ParseStringToDate parser = new ParseStringToDate(lastHolidayDate);
				if (parser.getThisDate() == null)	//If parsing failed
				{
					HolidayDateErrorMsg = parser.getErrorMsg();
					validatePass = false;
				}
				else								//If parsing succeeded
				{
					parsedLastHolidayDate = parser.getThisDateAsSQL();
					lastHolidayDate = parser.toString();
				}
			}
		}

		//Finally, decide whether to stay on this page or go back to List
		if (validatePass) {						//If Validation was successful
			HolidayDAO holidayDAO = 			//get DAO
					DAOFactory.getInstance().getHolidayDAO();
			HolidayBean holiday = new HolidayBean();
			holiday.setHoliday_name( lastHolidayName );
			holiday.setHoliday_date( parsedLastHolidayDate );
			if (editHolidayId == null)			//If this is "Add Holiday"
			{
				int tempI = 1;					//Generate Holiday ID
				try {
					tempI =holidayDAO.findNextHoliday();
				} catch (Exception e) {
					e.printStackTrace();
				}
				holiday.setHoliday_id(tempI);
				try {
					holidayDAO.addHoliday(holiday);	//Add to DB
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			else							//Otherwise this is "Edit Holiday"
			{
				holiday.setHoliday_id( Integer.parseInt(editHolidayId) );
				try {
					holidayDAO.updateHoliday(holiday);	//Update to DB
				} catch (Exception e) {
					e.printStackTrace();
				}				
			}	
			response.sendRedirect("HolidayList");		//Redirect here
		} else {																						//Otherwise Login failed, or this is first load
			request.setAttribute("PageTitle", pageTitle);
			request.setAttribute("ActionTargetTail", actionTargetTail);
			request.setAttribute("LastHolidayName", lastHolidayName);
			request.setAttribute("LastHolidayDate", lastHolidayDate);
			request.setAttribute("HolidayNameErrorMsg", HolidayNameErrorMsg);
			request.setAttribute("HolidayDateErrorMsg",HolidayDateErrorMsg );
			RequestDispatcher rd = request.getRequestDispatcher("HolidayDetail.jsp");
			rd.forward(request, response);												//Dispatch to View
		}
	}
}
